/*
 * 项目名称:    wms-server-jeecg
 * 创建人员:    DongPeng
 * 创建时间:    2023-10-06
 * copyright(c) 2022 无锡星智数服科技有限公司
 */
package org.jeecg.modules.dock.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dtflys.forest.http.ForestResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.dock.client.IBSRequestClient;
import org.jeecg.modules.dock.constant.SystemConstants;
import org.jeecg.modules.dock.entity.DockLightRecord;
import org.jeecg.modules.dock.entity.WmsLightConfig;
import org.jeecg.modules.dock.entity.light.request.IbsModelListVO;
import org.jeecg.modules.dock.entity.light.request.LightRequestVO;
import org.jeecg.modules.dock.entity.light.response.LightDetailsDTO;
import org.jeecg.modules.dock.entity.light.response.LightResponseDTO;
import org.jeecg.modules.dock.enums.LightResultStateEnum;
import org.jeecg.modules.dock.mapper.DockLightRecordMapper;
import org.jeecg.modules.dock.mapper.WmsLightConfigMapper;
import org.jeecg.modules.dock.service.LightIBSDockingService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 按灯系统控制服务实现
 *
 * @author DongPeng
 * @version 1.0.0
 * @date 2023-10-06
 * @description 类描述
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LightIBSDockingServiceImpl implements LightIBSDockingService {

    private final DockLightRecordMapper dockLightRecordMapper;

    private final WmsLightConfigMapper wmsLightConfigMapper;

    private final IBSRequestClient ibsRequestClient;
    @Override
    public int lightIBS(List<LightRequestVO> vo) {
        //判空
        if (ObjectUtil.isEmpty(vo)) {
            return 0;
        }
        //创建交互记录
        DockLightRecord dockLightRecord = new DockLightRecord();
        dockLightRecord.setSource(SystemConstants.WMS);
        dockLightRecord.setTarget(SystemConstants.IBS);
        dockLightRecord.setUuid(UUID.fastUUID().toString());
        dockLightRecord.setData(vo.toString());
        dockLightRecord.setSendTime(new Date());
        //发送请求
        IbsModelListVO requestVO = new IbsModelListVO();
        requestVO.setIbsModelList(vo);
        LightResponseDTO dto = null;
        try {
            ForestResponse<LightResponseDTO> response = ibsRequestClient.lightIBS(requestVO);
            if (response != null && StringUtils.isNotBlank(response.getContent()) ){
                JSONObject jsonObject = JSONObject.parseObject(response.getContent());
                dto = JSONObject.toJavaObject(jsonObject, LightResponseDTO.class);
            }
            if (response.getResult() != null && dto == null){
                dto = response.getResult();
            }
        }catch (Exception e) {
            dockLightRecord.setSendState(LightResultStateEnum.FAILURE.getRemark());
            dockLightRecord.setCause("调用时发生异常");
            dockLightRecordMapper.insert(dockLightRecord);
            throw new JeecgBootException("异常信息: " + e);
        }
        if (ObjectUtil.isEmpty(dto)) {
            dockLightRecord.setSendState(LightResultStateEnum.FAILURE.getRemark());
            dockLightRecord.setCause("接口无响应");
            dockLightRecordMapper.insert(dockLightRecord);
            return 0;
        }
        //有响应说明发送成功
        dockLightRecord.setSendState(LightResultStateEnum.SUCCESS.getRemark());
        dockLightRecord.setResultTime(new Date());
        dockLightRecord.setResultData(dto.toString());
        if (dto.getResult() == 0) {
            dockLightRecord.setResultState(LightResultStateEnum.FAILURE.getEnumName());
            dockLightRecord.setCause(dto.getMessage());
            dockLightRecordMapper.insert(dockLightRecord);
            return 0;
        }
        //details会包含错误信息
        if (dto.getResult() == 1 && ObjectUtil.isNotEmpty(dto.getDetails())) {
            dockLightRecord.setResultState(LightResultStateEnum.FAILURE.getEnumName());
            List<LightDetailsDTO> list = dto.getDetails();
            StringBuilder cause = new StringBuilder();
            list.forEach(detail -> {
                cause.append("对应灯具地址为: ").append(detail.getLocationId()).append(", ");
                cause.append("报错信息为: ").append(detail.getMessage()).append("; ");
            });
            dockLightRecord.setCause(cause.toString());
            dockLightRecordMapper.insert(dockLightRecord);
        }
        dockLightRecord.setResultState(LightResultStateEnum.SUCCESS.getEnumName());
        dockLightRecordMapper.insert(dockLightRecord);
        vo.forEach(light -> {
            String[] split = light.getLocationId().split("-");
            if (split.length == 2){
                WmsLightConfig config = wmsLightConfigMapper.selectOne(new LambdaQueryWrapper<WmsLightConfig>().eq(WmsLightConfig::getLocationId, split[0])
                        .eq(WmsLightConfig::getSiteCode,split[1]));
                //更新按灯配置表信息
                if (ObjectUtil.isNotEmpty(config)) {
                    config.setLightColor(light.getLightColor());
                    config.setState(light.getState());
                    wmsLightConfigMapper.updateById(config);
                }
            }

        });
        return 1;
    }
}
